package com.ce.socket;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

import org.apache.log4j.Logger;

import com.ce.study.socketpool.CM20JAVA;

public class SendByPoolCallable implements Callable<String> {
	private static Logger log = Logger.getLogger(SendByPoolCallable.class);
	private int execTimes;
	private ISocketPool pool;
	private byte[] msg;
	
	public SendByPoolCallable(ISocketPool pool, int execTimes) throws Exception {
		this.pool = pool;
		this.execTimes = execTimes;
		
	}
	
	public String call() throws Exception {
		int succeed = 0;
		int failed = 0;
		int dalFailed = 0;
		for (int i = 0; i < execTimes; i++) {
			try {
				String nonce = ""+System.currentTimeMillis();
				Map<String,String> mbody = new HashMap<String, String>();
				mbody.put("URI", "/dal/testnoauth/fcode.xml");
				mbody.put("METHOD", "GET");
				mbody.put("nonce", nonce);
				CM20JAVA reqmsg = new CM20JAVA(mbody);
				reqmsg.encode();
				msg = reqmsg.getMessage();
				byte[] rep = pool.sendData(msg, 1);
				CM20JAVA repmsg = new CM20JAVA(Map.class);
				repmsg.decode(rep);
				Object repObj = repmsg.getBodyObject();
				//System.out.println(repObj);
				if(repObj instanceof Map) {
					Map<String, String> mrep = (Map)repObj;
					String repNonce = mrep.get("nonce");
					if(!repNonce.equals(nonce)) {
						throw new Exception("send and receive nonce is not equal!");
					}
				}
				succeed++;
				Thread.sleep(10);
			} catch (DALException e) {
				dalFailed++;
				log.error("DalException", e);
			} catch (Exception e) {
				failed++;
				log.error("Exception", e);
			}
		}
		return execTimes+"|"+succeed+"|"+dalFailed+"|"+failed;
	}

}
